package main

import (
	"flag"
	"fmt"
	"os"
	"runtime"
	"time"

	"github.com/BurntSushi/toml"
)

type duration struct {
	time.Duration
}

func (d *duration) UnmarshalText(text []byte) error {
	var err error
	d.Duration, err = time.ParseDuration(string(text))
	return err
}

type Config struct {
	ZkAddrs            []string `toml:"zk_addrs"`
	HostAddr           string   `toml:"host_addr"`
	HeartBeatInterval  duration `toml:"heartbeat_interval"`
	Logfile            string   `toml:"logfile"`
	LogLevel           string   `toml:"loglevel"`
	ExecuterId         string   `toml:"executer_id"`
	ConcurrencyHandler int      `toml:"concurrency_handler"`
	ZkIpAndTimeNode    string   `toml:"zk_ipAndTime_path"`
	SubmitLogInterval  duration `toml:"submit_log_interval"`
	MaxPerLogSize      int      `toml:"max_per_log_size"`
	RecvJobTimeout     duration `toml:"recv_job_timeout"`
	LogResponseTimeout duration `toml:"log_response_timeout"`
	NoJobSleepTime     duration `toml:"nojob_sleep_time"`
}

var Conf Config

func init() {

	configFile := ParseConfig()
	_, err := toml.DecodeFile(configFile, &Conf)
	if err != nil {
		panic(err)
	}
}

func ParseConfig() string {
	filename := flag.String("c", "config.toml", "config file path")
	v := flag.Bool("version", false, "Print version info & exit")
	flag.Parse()
	if *v {
		PrintVersion()
		os.Exit(0)
	}
	return *filename
}

//VERSION
var (
	VERSION    = "0.0.0"
	BUILD_DATE = "0000-00-00 00:00:00"
	GitHash    = "000000"
)

var banner = `
---------------------------------------------------------
                      Squirrel Agent
Version:	%v
BuildTime:	%v
GitHash:	%v
GOVersion:	%v
---------------------------------------------------------
`

func PrintVersion() {
	fmt.Printf(banner, VERSION, BUILD_DATE, GitHash, runtime.Version())
}
